package controller

import (
	"config"
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"log"
	"model"
	"net/http"
	"spirit/mongodb"
	"spirit/utils"
	"spirit/utils/net"
	"strings"
)

type SystemUserController struct {
	Data interface{}
}

func (ctrl *SystemUserController) Router(router *gin.Engine) {
	systemUserGroup := router.Group("/system/user/")
	systemUserGroup.Use(sessionVerify())
	{
		systemUserGroup.GET("/add", systemUserAdd)
		systemUserGroup.GET("/edit", systemUserEdit)
		systemUserGroup.POST("/getUserInfo", getUserInfo)
		systemUserGroup.POST("/saveOrUpdateUser", saveOrUpdateUser)
		systemUserGroup.POST("/editUser", editUser)
	}
}

func getUserInfo(ctx *gin.Context) {
	result := &model.BaseResult{}
	session := sessions.Default(ctx)
	account := session.Get("account")
	role := session.Get("role")
	if account == nil || role == nil {
		result.Code = 1
		result.Msg = "用户信息为空请重新登录"
	} else {
		_role := role.(string)
		menus := config.Menus[_role]
		result.Code = 0
		result.Msg = "success"
		result.Data = map[string]interface{}{
			"name":      session.Get("name").(string),
			"organName": session.Get("organName").(string),
			"menus":     menus,
		}
	}
	ctx.JSON(http.StatusOK, result)
}

func systemUserAdd(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "system/system_user_add.html", gin.H{"organs": config.Organs})
}
func systemUserEdit(ctx *gin.Context) {
	session := sessions.Default(ctx)
	account := session.Get("account")
	name := session.Get("name")
	organName := session.Get("organName")
	ctx.HTML(http.StatusOK, "system/system_user_edit.html", gin.H{"name": name, "account": account, "organName": organName})
}

func saveOrUpdateUser(ctx *gin.Context) {
	result := &model.BaseResult{}
	m := make(map[string]interface{}, 0)
	data := net.RedingJsonDataFromRequestBody(ctx.Request)
	if data != "" {
		if err := json.Unmarshal([]byte(data), &m); err == nil {
			id := utils.SafeConvert2String(m["id"])
			password := utils.SafeConvert2String(m["password"])
			_password := utils.GetMd5String(password)
			m["password"] = _password
			organCode := utils.SafeConvert2String(m["organCode"])
			if organCode != "" {
				area := strings.Split(organCode, "-")[0]
				m["area"] = area
			}
			if id == "" {
				log.Printf("新增操作员用户:[%s],所属机构:[%s],角色:[%s],账户:[%s],原始密码:[%s]", m["name"], m["organName"], m["role"], m["account"], password)
				id = mongodb.Save(tbUser, m)
				if id != "" {
					result.Code = 0
					result.Msg = "用户保存成功"
					log.Printf("用户[%s]保存成功", m["name"])
				}
			} else {
				delete(m, "id")
				if b := mongodb.UpdateById(tbUser, id, m); b {
					result.Code = 0
					result.Msg = "用户更新成功"
					log.Printf("更新操作员用户:[%s] 成功", id)
				}
			}
		}
	}

	ctx.JSON(http.StatusOK, result)
}

func editUser(ctx *gin.Context) {
	result := &model.BaseResult{}
	account := ctx.Request.FormValue("account")
	oldPassword := ctx.Request.FormValue("oldPassword")
	newPassword := ctx.Request.FormValue("newPassword")
	accountI := sessions.Default(ctx).Get("account")
	_oldPassword := utils.GetMd5String(utils.SafeConvert2String(oldPassword))
	_newPassword := utils.GetMd5String(utils.SafeConvert2String(newPassword))
	result.Code = 1
	result.Msg = "密码修改失败"
	if accountI != nil && accountI.(string) == account {
		query := map[string]interface{}{}
		query["account"] = account
		query["password"] = _oldPassword
		re := mongodb.FindOne(tbUser, query)
		if re != nil && len(*re) > 0 {
			fmt.Println("用户信息:", re)
			d := *re
			id := utils.BsonIdToSId(d["_id"])
			d["password"] = _newPassword

			if b := mongodb.UpdateById(tbUser, id, d); b {
				result.Code = 0
				result.Msg = "密码修改成功"
				log.Printf("更新用户[%s]密码:成功", account)
			}
		} else {
			log.Printf("更新用户密码失败:用户[%s,%s]不存在", account, _oldPassword)
		}
	}
	ctx.JSON(http.StatusOK, result)
}
